<template>
  <div class="purchase-paln-wrap table-gl-w">
    <a-tabs @change="changeStatus" size="mini">
      <a-tab-pane v-for="tab in tabsList" :title="tab.title" :key="tab.key" />
    </a-tabs>
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap :showExport="true" :exportInfo="exportInfo" fromLocation="采购入库单" :seachData="seachData" :checkedList="selectIds" style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <p>共计{{ tableList.length }}条</p>
            <template v-if="searchVal.status == 10">
              <a-button type="primary" size="medium" @click="openSignStorage(selectIds)" v-if="$authPass('procurement.receipt.sign')">批量签收</a-button>
              <a-button class="gray-outline" size="medium" @click="reject(selectIds)" v-if="$authPass('procurement.receipt.sign')">批量拒收</a-button>
            </template>
            <a-button class="gray-outline" size="medium" @click="openPrintLabel(selectIds)" v-if="$authPass('procurement.receipt.print')">打印产品SKU</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table class="table-two-line" ref="tableListref" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ x: 1250, y: '100%' }">
            <template #columns>
              <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                <template v-if="item.dataIndex == 'sort'" #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
                <template v-else-if="item.dataIndex == 'purchaseNo'" #cell="{ record }">
                  <div class="flex-c-sb" style="padding-right: 20px">
                    <div class="order-w flex">
                      <div class="order-detail-item" style="width: 160px">
                        <div class="flex-c">
                          <span class="label">入库单号：</span>
                          <span class="highlight">{{ record.billNo }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.billNo" />
                        </div>
                        <div class="flex-c">
                          <span class="label">交货单号：</span>
                          <span class="highlight cursor">{{ record.deliveryNo }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.deliveryNo" />
                        </div>
                      </div>
                      <div class="order-detail-item" style="width: 220px">
                        <p><span class="label">入库仓：</span>{{ record.warehouseName }}({{ record.warehouseCode }})</p>
                      </div>
                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">提交人：</span>{{ record.createUname }}</p>
                        <p><span class="label">提交时间：</span>{{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">入库人：</span>{{ record.signUname }}</p>
                        <p><span class="label">入库时间：</span>{{ $setTime(record.gmtSign, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <p><span class="label">待入库：</span>{{ record.warehouseStayAmt }}</p>
                        <p><span class="label">已入库：</span>{{ record.warehouseRealAmt }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 140px">
                        <p><span class="label">退回数：</span>{{ record.warehouseReturnAmt }}</p>
                        <p><span class="label">入库货值：</span>￥{{ record.inventoryValue }}</p>
                      </div>
                    </div>
                    <a-space>
                      <a-button type="text" @click="toDetail(record)">详情</a-button>
                      <a-button type="text" v-if="searchVal.status == 10 && $authPass('procurement.receipt.sign')" @click="openSignStorage([record.id])">签收</a-button>
                      <a-button type="text" v-if="searchVal.status == 10 && $authPass('procurement.receipt.sign')" @click="reject([record.id])">拒收</a-button>
                    </a-space>
                  </div>
                </template>
              </a-table-column>
            </template>
            <template #expand-row="{ record }">
              <a-table class="table-singe-line show-border-table" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
                <template #columns>
                  <a-table-column :width="10" />
                  <a-table-column :width="40" />
                  <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                    <template v-if="item.dataIndex == 'sort'" #cell> </template>
                    <template v-else-if="item.dataIndex == 'purchaseNo'" #cell="option">
                      <div class="flex-c">
                        <span class="highlight">{{ option.record.purchaseNo }}</span>
                        <CopyText style="margin-left: 4px" class="edit-icon" :val="option.record.purchaseNo" />
                      </div>
                    </template>
                    <template v-else-if="item.dataIndex == 'shopName'" #cell="option">
                      <TextLimit :val="option.record.shopName" :rows="2" />
                    </template>
                    <template v-else-if="item.dataIndex == 'img'" #cell="option">
                      <ImgPopover :src="option.record.productImg">
                        <template #con>
                          <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                        </template>
                      </ImgPopover>
                    </template>
                    <template v-else-if="item.dataIndex == 'productName'" #cell="option">
                      <TextLimit :val="option.record.productName" />
                    </template>
                    <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                      <ShowSpuDetailBySku :val="option.record.sku" :showLimit="true" :rows="1" />
                      <p>{{ option.record.cateName }}</p>
                    </template>
                    <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                      <TextLimit :val="getProductSpecs(option.record)" />
                    </template>
                    <template v-else-if="item.dataIndex == 'rate'" #cell="option">
                      <p>{{ option.record.rate }}%</p>
                    </template>
                    <template v-else-if="['unitCosts', 'inventoryValue'].includes(item.dataIndex)" #cell="option">
                      <p>￥{{ option.record[item.dataIndex] }}</p>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 拒收-->
  <a-modal :width="500" v-model:visible="showRejectDialog" title="采购入库单拒收" title-align="start" :ok-loading="submitLoading" @cancel="refuseMsg = ''" :mask-closable="false" :on-before-ok="submitReject">
    <p style="margin-bottom: 10px">请再次确认是否需要拒收入库单</p>
    <a-textarea v-model="refuseMsg" style="height: 100px" placeholder="请填写拒收原因" allow-clear />
  </a-modal>
  <!-- 处理入库单 -->
  <SignStorage v-if="showSignStorage" :isShow="showSignStorage" :list="selectRows" @closed="showSignStorage = false" @success="getTableList" />
  <!-- 详情 -->
  <PurchaseInStorageDetail v-if="showDetailDialog" :isShow="showDetailDialog" :currentItem="currentData" @closed="showDetailDialog = false" />
  <!-- 批量打印SKU -->
  <printSkuLabel v-if="showPrintLabel" :isShow="showPrintLabel" :printConfig="printConfig" @closed="showPrintLabel = false" :list="printConfig.list" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { FilterTableItem, ExportInfo } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import SignStorage from './components/signStorage.vue'
  import PurchaseInStorageDetail from './components/purchaseInStorageDetail.vue'
  import { Message } from '@arco-design/web-vue'
  import { findReceiptPage, refuseReceiptOrder } from '@/api/purchase'
  import useBaseDataStore from '@/store/modules/base-data'
  import printSkuLabel from './components/printSkuLabel.vue'
  import { parseJson } from '@/utils'
  import { exportReceiptOrderSheet } from '@/utils/exportFiled'

  onMounted(async () => {
    getTableList()
    getShopList()
  })
  const tableColumns: Array<any> = [
    {
      title: '序号',
      dataIndex: 'sort',
      width: 40,
    },
    {
      title: '采购单号',
      dataIndex: 'purchaseNo',
      width: 110,
    },
    {
      title: '店铺',
      dataIndex: 'shopName',
      width: 100,
    },
    {
      title: '货主',
      dataIndex: 'salesmanName',
      width: 70,
    },
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      width: 100,
    },
    {
      title: 'SKU/类目',
      dataIndex: 'sku',
      width: 120,
    },
    {
      title: 'SKU规格',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: 'MSKU',
      dataIndex: 'msku',
      width: 100,
    },
    {
      title: '待入库数',
      dataIndex: 'warehouseStayAmt',
      width: 70,
    },
    {
      title: '已入库数',
      dataIndex: 'warehouseRealAmt',
      width: 70,
    },
    {
      title: '退回数量',
      dataIndex: 'warehouseReturnAmt',
      width: 70,
    },
    {
      title: '单件成本',
      dataIndex: 'unitCosts',
      width: 70,
    },
    {
      title: '入库货值',
      dataIndex: 'inventoryValue',
      width: 70,
    },
    {
      title: '货位',
      dataIndex: 'locationCode',
      width: 80,
    },
  ]
  const exportInfo: ExportInfo = {
    title: '导出采购入库单',
    type: 'single',
    supportAll: true,
    tabName: '导出采购入库单',
    fieldList: exportReceiptOrderSheet,
    supportTemplate: true,
    templateType: 'PURCHASE_STORAGE_ITEM',
    exportApi: 'exportReceiptOrder',
    excelName: '采购入库单',
  }
  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const tabsList = [
    { key: 10, title: '待入库' },
    { key: 20, title: '完成入库' },
    { key: 0, title: '已拒收' },
  ]
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'warehouseName',
      keyItems: [
        { label: '仓库名称', value: 'warehouseName' },
        { label: '仓库ID', value: 'warehouseCode' },
      ],
      keyWidth: '110',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: false,
    },
    {
      key: 'shopIds',
      label: '店铺',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [
        { label: 'SKU', value: 'skus' },
        { label: 'SPU', value: 'spus' },
        { label: 'MSKU', value: 'mskus' },
        { label: 'FNSKU', value: 'fnskus' },
        { label: '产品名称', value: 'productName' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_search',
      key: 'createUname',
      value: ref(),
      placeholder: '创建人',
      label: '创建人',
      width: 120,
    },
    {
      type: 'input_search',
      key: 'warehouseUname',
      value: ref(),
      placeholder: '处理人',
      label: '处理人',
      width: 120,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [
        { label: '提交时间', value: 'gmtCreate' },
        { label: '入库时间', value: 'gmtRefuse' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: 10,
  })
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const total = ref(0)
  const selectIds = ref([])
  const currentData = ref<any>({})
  const showSignStorage = ref(false)
  const filterData = ref<any>({})
  const tableListref = ref()
  const useBaseData = useBaseDataStore()
  const showRejectDialog = ref(false)
  const refuseMsg = ref()
  let currentIds: Array<string> = []
  const submitLoading = ref(false)
  const selectRows = ref<Array<any>>([])
  const tableListMap = ref({})
  const showDetailDialog = ref(false)
  const printConfig = ref<any>({})
  const showPrintLabel = ref(false)
  const seachData = ref<any>({})

  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopListAndShare()
    filterItem.value[1].optionItems = useBaseData.shopListAndShare.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
      }
    })
  }
  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findReceiptPage(params)
    seachData.value = params
    tableListref.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    expandable.value.expandedRowKeys = tableList.value.map((el: any) => el.id)
    tableList.value.forEach((el: any) => {
      tableListMap.value[el.id] = el
    })
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'purchaseNo') {
      return { rowspan: 1, colspan: 14 }
    }
  }
  // 显示详情
  function toDetail(row: any) {
    currentData.value = row
    showDetailDialog.value = true
  }
  function getSelectRows(ids: Array<string>) {
    selectRows.value = []
    ids.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  // 处理入库单
  function openSignStorage(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择入库单')
      return
    }
    getSelectRows(ids)
    showSignStorage.value = true
  }
  // 拒收二次确认
  function reject(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择入库单')
      return
    }
    currentIds = ids
    showRejectDialog.value = true
  }
  // 提交拒收
  async function submitReject() {
    if (!refuseMsg.value) {
      Message.error('请输入拒收原因')
      return false
    }
    const res: any = await refuseReceiptOrder({
      ids: currentIds,
      refuseMsg: refuseMsg.value,
    })
    if (!res) return false
    Message.success('已拒收')
    showRejectDialog.value = false
    refuseMsg.value = ''
    getTableList()
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 批量打印标签
  function openPrintLabel(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择入库单')
      return
    }
    getSelectRows(ids)
    let list: Array<any> = []
    selectRows.value.forEach((el: any) => {
      el.billItems.forEach((item: any) => {
        list.push({
          warehouseName: `${item.warehouseName}(${item.warehouseCode})`,
          billNo: el.billNo,
          productName: item.productName,
          img: item.productImg,
          sku: item.sku,
          warehouseAmt: item.warehouseAmt,
          salesmanName: item.salesmanName,
          id: item.id,
        })
      })
    })
    printConfig.value.tableColumns = [
      {
        title: '入库仓',
        dataIndex: 'warehouseName',
        isLimit: false,
        width: 120,
      },
      {
        title: '入库单',
        dataIndex: 'billNo',
        isLimit: false,
        width: 100,
      },
      {
        title: '产品名称',
        dataIndex: 'productName',
        isLimit: true,
        width: 120,
      },
      {
        title: '产品名称打印',
        dataIndex: 'productNamePrint',
        isLimit: false,
        width: 160,
      },
      {
        title: '图片',
        dataIndex: 'img',
        isLimit: false,
        width: 60,
      },

      {
        title: 'SKU',
        dataIndex: 'sku',
        isLimit: false,
        width: 120,
      },
      {
        title: '入库数',
        dataIndex: 'warehouseAmt',
        isLimit: false,
        width: 60,
      },
      {
        title: '打印数量',
        dataIndex: 'printNum',
        isLimit: false,
        width: 120,
      },
      {
        title: '销售员',
        dataIndex: 'salesmanName',
        isLimit: false,
        width: 70,
      },
    ]
    printConfig.value.allFieldList = {
      sku: { name: '产品SKU', key: 'sku', defaultVal: 'WME20815KP', fontSize: 10, sort: 1, isBold: 1 },
      productName: { name: '产品名称', key: 'productName', defaultVal: 'Horse Gifts for Women', fontSize: 8, lengthLimit: 25, sort: 5 },
      productNamePrint: { name: '产品名称打印', key: 'productNamePrint', defaultVal: 'Horse Gifts for Women', fontSize: 8, lengthLimit: 25, sort: 6 },
      warehouseAmt: { name: '入库数', key: 'warehouseAmt', defaultVal: '12', fontSize: 10, sort: 2, lLabel: '*' },
      salesmanName: { name: '销售员', key: 'salesmanName', defaultVal: '张三', fontSize: 10, sort: 3 },
      billNo: { name: '入库单号', key: 'billNo', defaultVal: 'IN23101820', fontSize: 10, sort: 4 },
    }
    printConfig.value.fieldList = ['sku', 'productName', 'salesmanName', 'warehouseAmt']
    printConfig.value.list = list
    showPrintLabel.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  .edit-icon {
    display: none;
  }
  :deep(.arco-table-tr-expand tr:hover) {
    .arco-table-td {
      background-color: var(--color-fill-1) !important;
    }
    .edit-icon {
      display: inline-block;
    }
  }

  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .order-w {
    color: #666;
    flex: 1;
    &:hover {
      .edit-icon {
        display: inline-block;
      }
    }
    .order-detail-item {
      width: 200px;
    }
  }
</style>
